<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\Admin\CoinRecords;
use App\Models\CoinRecord;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CoinRecordsController extends Controller
{
    /**
     * 游戏币流水记录
     *
     * @param Request $request
     * @return CoinRecords
     */
    public function index(Request $request)
    {
        $where = [];
        
        if ($request->filled('user_id')) {
            $where['user_id'] = $request->get('user_id');
        }
        
        $paginate = CoinRecord::with('user')->where($where)->orderByDesc('id')->paginate(per_page());
        
        return new CoinRecords($paginate);
    }
    
    /**
     * “系统赠送”游戏币
     *
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $inputs = $this->validate($request, [
            'coin' => 'required|integer|min:1|max:1000',
        ]);
        
        /** @var \App\Models\User $user */
        $user = User::findOrFail($request->post('user_id'));
        
        CoinRecord::create([
            'user_id' => $user->id,
            'coin' => $inputs['coin'],
            'recordable_type' => CoinRecord::TYPE_SYSTEM,
            'recordable_id' => 0,
        ]);
        
        $user->increment('coin', $inputs['coin']);
        
        return $this->wrapData();
    }
    
    /**
     * 统计
     *
     * @return array
     */
    public function statistics()
    {
        $isToday = request('today', false);
        
        $queryClosure = function ($query) {
            $today = Carbon::today();
            $tomorrow = Carbon::tomorrow();
            
            return $query->whereBetween('created_at', [$today, $tomorrow]);
        };
        
        // 购买
        $payment = CoinRecord::where('recordable_type', CoinRecord::TYPE_PAYMENT)
            ->when($isToday, $queryClosure)->sum('coin');
        
        // 消费
        $consume = CoinRecord::where('recordable_type', CoinRecord::TYPE_GAME_RECORD)
            ->when($isToday, $queryClosure)->sum('coin');
        
        // 赠送
        $present = CoinRecord::whereIn('recordable_type', [
            CoinRecord::TYPE_PAYMENT_AWARD,
            CoinRecord::TYPE_REGISTER,
            CoinRecord::TYPE_SYSTEM,
        ])->when($isToday, $queryClosure)->sum('coin');
        
        $data = [
            'payment' => $payment,
            'consume' => $consume,
            'present' => $present,
        ];
        
        return $this->wrapData($data);
    }
}
